package com.zhai.boot.global;

import com.zhai.boot.common.ServiceResult;
import com.zhai.boot.common.ServiceResultConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.List;

/**
 * @package: com.zhai.boot.global
 * @project-name: zhai-boot
 * @description: 统一异常处理
 * @author: Created by 翟凤玺
 * @create-datetime: 2018-7-25 17:09
 */
@Slf4j
@RestControllerAdvice
public class GlobaExceptionHandler {

    public static final String NULL_ERROR_MSG = "空指针异常";
    public static final String SYMBOL = "；";
    public static final String VALID_ERROR_CODE = "-10";
    /**
     * 运行时异常处理
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<ServiceResult> exceptionHandler(RuntimeException e) {

        if (e instanceof NullPointerException) {
            log.error(NULL_ERROR_MSG, e);
            return ResponseEntity.ok().body(ServiceResult.failure(ServiceResultConstant.SYS_ERROR));
        }
        log.error(ServiceResultConstant.SYS_ERROR.getCode(), e);
        return ResponseEntity.ok().body(ServiceResult.failure(ServiceResultConstant.SYS_ERROR));
    }

    /**
     * 字段校验异常处理
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ServiceResult> validHandler(MethodArgumentNotValidException e) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuilder errors = new StringBuilder();
        for (ObjectError error : allErrors) {
            errors.append(error.getDefaultMessage()).append(SYMBOL);
        }
        return ResponseEntity.ok().body(ServiceResult.failure(VALID_ERROR_CODE, errors.toString()));
    }

}
